<?php

namespace Modules\Comment\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use Modules\Comment\Models\Comment;
use Illuminate\Http\Request;
use Modules\Comment\Http\Resources\CommentResource;
use Modules\Good\Models\Good;

class CommentController extends BaseController
{
    public function index(Request $request)
    {
        $rate=$request->query('rate');
        $good_title=$request->query('good_title');

        $allowedIncludes = ['user', 'good'];
        //请求链接找参数是’include‘参数，如果有值则返回字符串"user,good" 
        //explode分割字符串为数组：['user','good'] array_filter过滤空值
        //最终$includes=['user','good']
        $includes = array_filter(explode(',', $request->query('include', '')));

        $comments=Comment::query()
        //返回一个Eloquent查询构造器对象（Illuminate\Database\Eloquent\Builder）         
        //实际执行的SQL语句：select * from `comments` Comment对应comments表
        
        // when发现$rate有值，则执行闭包
        //Laravel的when方法会把 当前的查询构造器自动传给闭包
        //此处$query也就是上方query()返回对象
        ->when($rate,function($query) use ($rate){
            // where('rate',$rate);等价于 WHERE rate = ?
            $query->where('rate',$rate);
        })

        //有$good_title则执行function，没有则不执行
        ->when($good_title,function($query) use ($good_title){
            //Good模型对应goods表 在goods表里模糊查询title字段
            //->pluck('id') 只拿这些的id列
            $goods_id=Good::where('title','like','%'.$good_title.'%')->pluck('id');
            $query->whereIn('good_id',$goods_id);
        })
        ->when(!empty($includes), function($query) use ($includes, $allowedIncludes) {
            //array_intersect交集，找出两数组都存在的值
            $validIncludes = array_intersect($includes, $allowedIncludes);
            if (!empty($validIncludes)) {
                //不为空，则进行with关联查询 预加载出
                $query->with($validIncludes);
            }
        })
        ->paginate(2);
        return CommentResource::collection($comments);
    }
    public function show(Request $request,$id){
        $comment=Comment::find($id);
        if(!$comment){
            return response()->json(['message'=>'评论不存在'],404);
        }
        return new CommentResource($comment);
    }
public function reply(Request $request, $id)
{
    $request->validate(['reply' => 'required|string',], [
        'reply.required' => '回复内容不能为空',
        'reply.string'   => '回复内容必须是字符串',
    ]);
    $comment=Comment::find($id);
    if(!$comment){
        return response()->json(['message'=>'评论不存在'],404);
    }
    $comment->reply=$request->input('reply');
    $comment->save();
    return new CommentResource($comment);
}

}
